import Dexie from 'dexie';

// 创建数据库
export const db = new Dexie('AI_CHAT');

// 定义数据表
db.version(1).stores({
//
    // user:'id,name,nick,email,phone,avator',
    messages:'++id,group_id,role,content,files,thinking_content,thinking_enabled,thinking_elapsed_secs,search_enabled,search_results,search_status,content_secs,parent_id,comment,isLike,isDelete,time',
    groups:"++id,title,desc,time",
    current:"gid",
    config:'',
});

// 数据表基础操作

// 获取当前 group Id

// 获取所有分组信息
export const getAllGroups = async () => {
    return await db.groups.toArray();
}

// 获取最近的分组 id


// 添加新的分组
export const addGroup = (data = {}) => {
    return db.groups.put(Object.assign({time:new Date().getTime()},data))
}

// 修改分组信息
export const updateGroup = async (gid,data) => {
    await db.groups.update(gid,data)
}

// 删除分组以及分组下的所有数据
export const delGroup = async (gid) => {
    await db.groups.delete(gid);
    await db.messages.where('group_id').equals(gid).delete();
}


// 获取分组信息
export const getGroup = (gid) => {
    return db.groups.get(gid)
}

//
export const getLatestGroup = async () => {
    return await db.groups.desc().first();
}

// 获取指定分组的所有对话记录
export const getGroupMessages = async (gid) => {
    return await db.messages.where('group_id').equals(gid).toArray()
}

// 获取指定分组下某条消息和之前的所有对话记录 也可以删除后面的所有记录
export const getGroupPreMessages = async (gid,mid,isDelete = false) => {
    const arr = await getGroupMessages(gid);
    const res = [];
    let b = true;
    for(const d of arr){
        if(b){
            res.push(d)
        }else{
            if(isDelete){
                db.messages.delete(d.id)
            }
        }
        if(d.id == mid){
            b = false;
        }
    }

    return res;
}

// 
// 获取 message
export const getMessage = async(mid) => {
    return await db.messages.get(mid)
}
// 新增 message
export const addMessage = (data) => {
    return db.messages.put(Object.assign({time:new Date().getTime()},data))
}
// 修改 message
export const updateMessage = (mid,data) => {
    return db.messages.update(mid,data)
}

// 删除消息
export const delMessage = (mid) => {
    db.messages.delete(mid)
}

// 评价信息
export const commentMessage = (mid,td) => {
    const data = {isLike:true,comment:null}
    if(td !== true){
        data.isLike = false;
        data.comment = td;
    }
    updateMessage(mid,data)
}

// 重新生成内容 编辑用户信息重新生成，重新生成回答
export const resetMessage = async (smid,td) => {
    const {parent_id} = await getMessage(smid)
    const data = Object.assign({parent_id},td)
    addMessage(data)
}
// 

